package com.lsh.payment.core.util.ftp;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPClientConfig;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import sun.net.TelnetInputStream;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * Project Name: lsh-payment
 *
 * @author peter
 * @date 17/11/1
 * 北京链商电子商务有限公司
 * Package
 * desc:
 */
@Slf4j
public class FtpMannager {
    /**
     * FTP客户端
     */
    private FTPClient ftpClient;

    /**
     * 服务器连接
     *
     * @param ip       服务器IP
     * @param port     服务器端口
     * @param user     用户名
     * @param password 密码
     * @param workPath 服务器路径
     * @throws
     */
    public void connectServer(String ip, int port, String user, String password, String workPath) throws Exception {
        try {
            /* ******连接服务器的两种方法****** */
            // 第一种方法

            ftpClient = new FTPClient();
            ftpClient.connect(ip, port);
            ftpClient.login(user, password);
            // 设置成2进制传输
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            System.out.println("login success!");
            ftpClient.setFileTransferMode(FTPClient.STREAM_TRANSFER_MODE);
            //判断是否连接成功
            int reply = ftpClient.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftpClient.disconnect();
                System.out.println("FTP server refused connection.");
                return;
            }

            //设置访问被动模式
            ftpClient.setRemoteVerificationEnabled(false);
            ftpClient.enterLocalPassiveMode();
            ftpClient.setControlEncoding("UTF-8");

            FTPClientConfig conf = new FTPClientConfig(FTPClientConfig.SYST_UNIX);
            ftpClient.configure(conf);

            ftpClient.changeWorkingDirectory(workPath);

        } catch (IOException ex) {
            ex.printStackTrace();
            throw new RuntimeException(ex);
        }

    }

    /**
     * 关闭连接
     */

    public void closeConnect() {
        try {
            ftpClient.disconnect();
            System.out.println("disconnect success");
        } catch (IOException ex) {
            System.out.println("not disconnect");
            ex.printStackTrace();
            throw new RuntimeException(ex);
        }
    }

    /**
     * 下载文件
     *
     * @param remoteFile    远程文件路径(服务器端)
     * @param localPathFile 本地文件路径(客户端)
     * @throws
     */
    public void download(String remoteFile, String localPathFile) throws Exception {
        TelnetInputStream is = null;
        FileOutputStream os = null;
        try {
            FTPFile[] files = ftpClient.listFiles();
            for (FTPFile f : files) {
                log.info("【收钱吧下载对账单名称】- " + f.getName());
                if (f.getName().equals(remoteFile)) {
                    log.info("收钱吧下载对账单  下载开始");
                    File file = new File(localPathFile);
                    OutputStream ios = new FileOutputStream(file);
                    ftpClient.retrieveFile(new String(f.getName().getBytes("UTF-8"), "ISO-8859-1"), ios);
                    ios.close();
                    break;
                }
            }
        } catch (IOException ex) {
            log.info("收钱吧下载对账单失败", ex);
            throw new RuntimeException(ex);
        } finally {
            try {
                if (is != null) {
                    is.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (os != null) {
                        os.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * @param ip
     * @param port
     * @param user
     * @param password
     * @param workPath
     * @param remoteFile
     * @param localPathFile
     * @return
     * @throws Exception
     */
    public boolean dealFtp(String ip, int port, String user, String password, String workPath, String remoteFile, String localPathFile) throws Exception {

        FtpMannager ftp = null;
        boolean dealFlag = false;
        try {
            ftp = new FtpMannager();

            ftp.connectServer(ip, port, user, password, workPath);

            ftp.download(remoteFile, localPathFile);

            dealFlag = true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != ftp) {
                ftp.closeConnect();
            }
        }

        return dealFlag;
    }

    /**
     * 函数入口
     *
     * @param agrs
     */
    public static void main(String agrs[]) {

        /*
         * 使用默认的端口号、用户名、密码以及根目录连接FTP服务器
         */
        FtpMannager ftp = null;
        try {
            ftp = new FtpMannager();

            ftp.connectServer("ftp.shouqianba.com", 21, "R_LIANSHANG_WOSAI", "LianShang1234", "201904");

            ftp.download("1680002144931_链商-2019-04-26-2019-04-27.xlsx", "/Users/peter/logs/cm/201904/");

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != ftp) {
                ftp.closeConnect();
            }

        }


    }

}